package utils

import (
	"golang.org/x/net/context"
	"google.golang.org/grpc"
)

//rpc代理
type RpcProxy struct {
	net     string           //协议类型
	address string           //地址
	client  *grpc.ClientConn //客户端
	iskeep  bool             //是否连接
	ctx     context.Context
}

func (r *RpcProxy) Context() context.Context {
	return r.ctx
}

func (r *RpcProxy) Conn() *grpc.ClientConn {
	return r.client
}

func (r *RpcProxy) Close() {
	r.iskeep = false
	r.client.Close()
}

func (r *RpcProxy) Status() bool {
	return r.iskeep
}

func (r *RpcProxy) Start() error {
	client, err := grpc.Dial(r.address, grpc.WithInsecure())
	if err == nil {
		r.client = client
		r.ctx = context.Background()
		r.iskeep = true
		return nil
	}
	return err
}

var _instance *RpcProxy

func NewRpcProxy(network, address string) *RpcProxy {
	if _instance == nil {
		_instance = &RpcProxy{
			net:     network,
			address: address,
			iskeep:  false,
		}
	}
	return _instance
}
